import React, { useState, useRef } from 'react';
import { Card, Input, Button, Upload, message, Slider, Row, Col } from 'antd';
import type { UploadProps } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import CommonTour, { TourGuideButton } from '@/components/CommonTour';

const { TextArea } = Input;
const { Dragger } = Upload;

const SceneFragmentation: React.FC = () => {
  const [description, setDescription] = useState<string>('');
  const [imageUrl, setImageUrl] = useState<string>('');
  const [fragmentCount, setFragmentCount] = useState<number>(4);
  const [loading, setLoading] = useState<boolean>(false);
  const [tourVisible, setTourVisible] = useState(false);
  
  // Tour相关的ref引用
  const uploadRef = useRef<HTMLDivElement>(null);
  const descriptionRef = useRef<HTMLDivElement>(null);
  const fragmentCountRef = useRef<HTMLDivElement>(null);
  const generateRef = useRef<HTMLButtonElement>(null);
  const resultRef = useRef<HTMLDivElement>(null);
  
  // 组织所有ref为一个对象
  const tourRefs = {
    upload: uploadRef,
    description: descriptionRef,
    fragmentCount: fragmentCountRef,
    generate: generateRef,
    result: resultRef,
  };
  
  // 显示导览
  const showTour = () => {
    // 添加短暂延迟确保DOM已渲染
    setTimeout(() => setTourVisible(true), 100);
  };
  
  // Tour步骤配置
  const tourSteps = [
    {
      key: 'upload',
      title: '上传场景图片',
      description: '点击或拖拽文件上传您需要裂变的场景图片',
    },
    {
      key: 'description',
      title: '填写描述',
      description: '描述您想要裂变的场景类型和变化需求，帮助AI更好理解您的需求',
    },
    {
      key: 'fragmentCount',
      title: '设置裂变数量',
      description: '通过滑块调整您需要生成的裂变图片数量，范围为2-8张',
    },
    {
      key: 'generate',
      title: '生成按钮',
      description: '点击此按钮开始生成场景裂变图片',
    },
    {
      key: 'result',
      title: '生成结果',
      description: '下方区域将显示生成的场景裂变图片，您可以下载所有图片或重新生成',
    },
  ];

  const uploadProps: UploadProps = {
    name: 'file',
    multiple: false,
    action: '/api/upload',
    onChange(info) {
      const { status } = info.file;
      if (status === 'done') {
        message.success(`${info.file.name} 文件上传成功`);
        setImageUrl(URL.createObjectURL(info.file.originFileObj as File));
      } else if (status === 'error') {
        message.error(`${info.file.name} 文件上传失败`);
      }
    },
    onDrop(e) {
      console.log('Dropped files', e.dataTransfer.files);
    },
  };

  const handleGenerate = () => {
    if (!description || !imageUrl) {
      message.warning('请填写描述并上传图片');
      return;
    }

    setLoading(true);
    // 模拟AI生成过程
    setTimeout(() => {
      message.success('场景裂变图片生成成功');
      setLoading(false);
    }, 3000);
  };

  return (
    <>
      <div className="p-4">
        <h2 className="text-xl font-bold mb-4" style={{ display: 'flex', alignItems: 'center' }}>
          场景裂变
          <TourGuideButton onClick={showTour} />
        </h2>
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <Card title="上传场景图片" className="h-full">
          <div ref={uploadRef}>
            <Dragger {...uploadProps}>
              <p className="ant-upload-drag-icon">
                <InboxOutlined />
              </p>
              <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
              <p className="ant-upload-hint">
                支持单个图片文件上传，用于场景裂变
              </p>
            </Dragger>
          </div>
        </Card>
        <Card title="生成参数" className="h-full">
          <div ref={descriptionRef}>
            <TextArea
              rows={4}
              placeholder="请描述您想要裂变的场景类型和变化需求"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              className="mb-4"
            />
          </div>
          <div ref={fragmentCountRef} className="mb-4">
            <Row>
              <Col span={24}>
                <label className="block mb-2">裂变数量: {fragmentCount}</label>
              </Col>
              <Col span={24}>
                <Slider
                  min={2}
                  max={8}
                  value={fragmentCount}
                  onChange={setFragmentCount}
                  marks={{
                    2: '2',
                    4: '4',
                    6: '6',
                    8: '8'
                  }}
                />
              </Col>
            </Row>
          </div>
          <Button ref={generateRef}  style={{ marginTop: '16px' }} type="primary" onClick={handleGenerate} loading={loading} block>
            生成场景裂变图片
          </Button>
        </Card>
      </div>
      {imageUrl && (
        <Card title="生成结果" className="mt-4">
          <div ref={resultRef} className="flex flex-wrap justify-center gap-4">
            {/* 模拟裂变结果 */}
            {Array.from({ length: fragmentCount }).map((_, index) => (
              <div key={index} className="scene-fragment">
                <img src={imageUrl} alt={`场景裂变结果 ${index + 1}`} className="max-w-[200px] max-h-[200px]" style={{ 
                  maxWidth: '100vw', 
                  maxHeight: '60vh',
                  margin: '0 auto'
                }} />
              </div>
            ))}
          </div>
          <div className="flex justify-center mt-4">
            <Button className="mr-2">下载所有图片</Button>
            <Button type="primary">重新生成</Button>
          </div>
        </Card>
      )}
    </div>
    
    <CommonTour
      open={tourVisible}
      onClose={() => setTourVisible(false)}
      steps={tourSteps}
      targetRefs={tourRefs}
    />
  </>
  );
};

export default SceneFragmentation;